<?php
require(dirname(dirname(__FILE__))."/Config/config.php");
require(dirname(dirname(__FILE__))."/jssdk.php");
class rchatController extends appController{
	public $wxid = 0;//数据库Id
	
	public $m;//自己的model
	public $info=array();//当前用户的微信信息
	public  function __construct(){
		parent::__construct();
	
		//基础信息构建
// 		$_SESSION['wxid'] = 1;
		$this->m = Model('rchat');
		
	
		//当前用户的微信id
		$this->wxid = $_SESSION['wxid']?$_SESSION['wxid']:0;
		
		if($this->wxid>0)
		{
			//当前用户的微信信息
			$this->info = $this->m->get_record($this->wxid);
			$this->assign('info',$this->info);
		}
	}
	
	public function set()
	{
		$_SESSION['wxid']=$_GET['wxid'];
	}
	public function setYao()
	{
		$_SESSION['yaoWxid']=$_GET['yaoWxid'];
	}
	//清除数据
	public function clear()
	{
	
		unset($_SESSION['wxid']);
		unset($_SESSION['pid']);
		unset($_SESSION['yaoWxid']);
		echo "已清除数据";
		exit;
	}
	
	//需要授权才可进入游戏
	public function canIn()
	{
		if(!$this->info)
		{
			header("Location:http://".$_SERVER['HTTP_HOST']."/ws/index.php?g=home&m=rchat&a=index");
			exit;
		}
	}
	
	//微信访问地址
	public function index(){
		
			//是否已授权
			$this->check_member();
			
			//微信分享参数构建
			$jsdk = $this->m ->get_jsdk();
			 
			$this->assign("jsdk", $jsdk);
			
			$cfg = $this->m->get_cfg();
			$time = yf_time();
			$config[c] = array('site_name' => "G4弹幕-".$cfg['site_name']);
			$this->assign_global($config);
			$this->m->updateFrontTime($cfg['frontTime']);
			$special_ad = $this->m->get_special_ad();//话题banner
			$this->assign('Ad',$special_ad[0]);//默认
			$this->assign('specialAd',json_encode($special_ad));
			//记录登陆信息
			$this->m->save_visitor($this->info['openid']);
			
			$timestamp =intval($cfg['timestamp']);
			$refresh = intval($cfg['refreshtime']);
			$commentDayMax = intval($cfg['commentDayMax']);
			$commentMinuteMax = intval($cfg['commentMinuteMax']);
			$chatMaxNum = intval($cfg['chatMaxNum']);
			$staggerTime = intval($cfg['staggerTime']);
			//获取个人当天评论的个数
			$commentDayNum = $this->m->get_comment_num($this->wxid);
			
			$this->assign("timestamp", $timestamp+intval($cfg['frontTime']));
			$this->assign('timeout',$refresh-($time-$timestamp)%$refresh);
			$this->assign('refreshtime',$refresh);
			$this->assign('commentDayMax',$commentDayMax);
			$this->assign('commentMinuteMax',$commentMinuteMax);
			$this->assign('commentDayNum',$commentDayNum);
			$this->assign('placeholder',$cfg['placeholder']);
			$this->assign('staggerTime',$staggerTime);
			$this->assign('chatMaxNum',$chatMaxNum);
			
			
			
			$result = $this->m->get_special_chat($this->wxid,$commentDayNum);
			$this->assign('rule', json_encode($result));//单日
			
			$this->assign("now", $time);
			$this->display('index.html');
	}
	
	
	/**
	 * 保存评论
	 * @return text
	 */
	public function saveComment(){
		$this->canIn();
		$data['comment'] = $_POST['text'];
		$data['wxid'] = $this->wxid;
		$data['status'] =0;
		$res =$this->m->create_record($data);
		print_r(json_encode($res));
	}
	
	
	public function addClickAd(){
		$id= isset($_POST['id'])?$_POST['id']:"";
		$res = array("error"=>1);
		if($id){
			if($this->m->add_click_num($id)){
				$res['error']=0;
			}
		}
		print_r(json_encode($res));
	}
	
	//首页接口
	public function get_user_info(){
		if(!isset($_SESSION['yaoWxid'])){
			$access_token = $this->getYaoAccessToken();
			$path = ROOT_PATH."Admin/Config/yaotv.json";
			$data = json_decode(file_get_contents($path), true);
			$appid = $data['yaoappid'];
			$user_info = $this->return_user_info($appid, $access_token, $_REQUEST['code']);
			if(!isset($user_info['openid'])){
				$res['error'] = 1;
				$res['content'] = "请重新登录";
				unset($_SESSION['yaoWxid']);
				die($_REQUEST['callback']."(".json_encode($res).")");
			}
			$a = Model('app');
			$check_openid = $a->get_count_openid($user_info['openid']);
			if($check_openid == 0)
			{
				$info['openid'] = $user_info['openid'];
				$info['nickname'] = $user_info['nickname'];
				$info['sex'] = $user_info['sex'];
				$info['headimgurl'] = $user_info['headimgurl']."/64";
				$wxid =$a->insert_into_wxuser($info);
				if(!$wxid)
				{
					echo "System Error! Please wait for a while!";
				}
			}
			else
			{
				$wxid = $a->get_wxid($user_info['openid']);
			}
			$_SESSION['yaoWxid'] = $wxid;
			//当前用户的微信信息
			$this->info = $this->m->get_record($_SESSION['yaoWxid']);
			$res['error'] = 0;
			$res['result'] = $this->info;
			die($_REQUEST['callback']."(".json_encode($res).")");
		}else{
			//当前用户的微信信息
			$this->info = $this->m->get_record($_SESSION['yaoWxid']);
			$res['error'] = 0;
			$res['result'] = $this->info;
			die($_REQUEST['callback']."(".json_encode($res).")");
		}
	}
	
	
	public function getYaoAccessToken(){
		$path = ROOT_PATH."Qiaqia/Json/yao_access_token.json";
		$data = json_decode(file_get_contents($path), true);
		if(empty($data['access_token']) || $data['expire_time'] < yf_time()){
				
			$path2 = ROOT_PATH."Admin/Config/yaotv.json";
			$data2 = json_decode(file_get_contents($path2), true);
			$app['appid'] = $data2['yaoappid'];
			$app['appsecret'] = $data2['yaoappSecret'];
			$new_info = $this->getToken($app['appid'], $app['appsecret']);
			$info['access_token'] = $new_info['access_token'];
			$info['expire_time'] = yf_time() + 1500;
			$fp = fopen($path, "w");
			fwrite($fp, json_encode($info));
			fclose($fp);
			return $new_info['access_token'];
		}else{
			return $data['access_token'];
		}
	}
	
	public function getToken($appid,$secret){
		$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$result = curl_exec($ch);
		$token = json_decode($result);
		$yf_info['access_token'] = $token->access_token;
		$yf_info['expires_in'] = $token->expires_in;
		return $yf_info;
	}
	
	public function return_user_info($appid,$access_token,$code){
		$url = "https://api.weixin.qq.com/yaotv/user/userinfo?appid=".$appid."&access_token=".$access_token."&code=".$code;
		$json = file_get_contents($url);//获取微信用户基本信息
		$arr = json_decode($json,true);
		if($arr["openid"]){
			$this->write_log($arr['openid'], $code);
		}else{
			$this->write_error($arr, $url);
		}
		return $arr;
	}
	
	public function write_log($openid,$code){
		$file = ROOT_PATH."Qiaqia/Log/tv_err.log";
		$content = "wxid：".date("Y-m-d H:i:s").": code:".$code." openid:".$openid.PHP_EOL;
		$f  = file_put_contents($file, $content,FILE_APPEND);
	}
	
	public function write_error($error,$url)
	{
		$file = ROOT_PATH."Qiaqia/Log/tv_errmsg.log";
		$content = "error：".date("Y-m-d H:i:s").": url:".$url.PHP_EOL." errMsg:{".PHP_EOL;
		foreach($error as $k=>$v){
			$content.=" $k => $v;".PHP_EOL;
		}
		$content."}".PHP_EOL;
		$f  = file_put_contents($file, $content,FILE_APPEND);
	}
	public function saveHongbaoInfo(){
		$info['wxid'] = isset($_GET['wxid'])?$_GET['wxid']:$_SESSION['yaoWxid'];
		$info['hongbao_id']  = $_GET['hongbao_id'];
		$info['addtime'] = $_SERVER['REQUEST_TIME'];
		$id = $this->m->insert($info,"get_hongbao_user");
	}
	
	public function get_hongbao_sign(){
		$a = Model('app');
		$openid = $a->get_openid($_GET['wxid']);
		if(!$openid){
			$res['error'] = 1;
			$res['content'] = "请重新登录";
			die($_REQUEST['callback']."(".json_encode($res).")");
		}
		$noncestr = hy_rand(28);
	
		$lottery_id =Model('chat')->get_luckyDraw($_GET['hongbao_id']);
		if(isset($_GET['captcha'])){//有值
			$captcha = $_GET['captcha'];
			$post_data = array(
					"captcha"=>$captcha,
					"lottery_id"=>$lottery_id,
					"noncestr"=>$noncestr,
					"userid"=>$openid,
			);
		}else{
			$post_data = array(
					"lottery_id"=>$lottery_id,
					"noncestr"=>$noncestr,
					"userid"=>$openid,
			);
		}
		$path2 = ROOT_PATH."Admin/Config/yaotv.json";
		$data2 = json_decode(file_get_contents($path2), true);
		$stringA = $this->ToUrlParams($post_data)."&key=".$data2['key'];
		$post_data['sign']=strtoupper(md5($stringA));
		$res['error'] = 0;
		$post_data['captcha'] = isset($post_data['captcha'])?$post_data['captcha']:"";
		$res['result'] = $post_data;
		print_r($_REQUEST['callback']."(".json_encode($res).")");
	}
	
	public function getHomeInfo()
	{
		//获取上面banner
		$result = $this->m->getHomeInfo();
		
		
		$hongbao_id = intval($this->m->get_now_hongbaoId());
		$result['hongbao_id'] = $hongbao_id;
		$cfg = $this->m->get_cfg();
		$result['isShowHongbao'] = $cfg['isShowHongbao'];
		$result['isShowAlert'] = $cfg['isShowAlert'];
		
		print_r($_REQUEST['callback']."(".json_encode($result).")");
	}
	
	public function getJsdk()
	{
		//微信分享参数构建
		$jsdk = $this->m ->get_jsdk_post();
		$result = array("error"=>0,"jsdk"=>$jsdk);
		print_r($_REQUEST['callback']."(".json_encode($result).")");
	}
	
	
	public function toTvShare()
	{
		$url = $this->parseurl("http://yaotv.qq.com/shake_tv/auto2/2015/12/8rzm5oiibd3bh7/index.html");
		header('Location:http://yao.qq.com/tv/entry?redirect_uri='.$url);
		exit();
	}
	
	//微信访问地址
	public function indexFensi(){
	
		//是否已授权
		$this->check_member();
			
		//微信分享参数构建
		$jsdk = $this->m ->get_jsdk();
	
		$this->assign("jsdk", $jsdk);
			
		$cfg = $this->m->get_cfg();
		$time = yf_time();
		$config[c] = array('site_name' => "G4弹幕-".$cfg['site_name']);
		$this->assign_global($config);
		$this->m->updateFrontTime($cfg['frontTime']);
		$special_ad = $this->m->get_special_ad();//话题banner
		$this->assign('Ad',$special_ad[0]);//默认
		$this->assign('specialAd',json_encode($special_ad));
		//记录登陆信息
		$this->m->save_visitor($this->info['openid']);
			
		$timestamp =intval($cfg['timestamp']);
		$refresh = intval($cfg['refreshtime']);
		$commentDayMax = intval($cfg['commentDayMax']);
		$commentMinuteMax = intval($cfg['commentMinuteMax']);
		$chatMaxNum = intval($cfg['chatMaxNum']);
		$staggerTime = intval($cfg['staggerTime']);
		//获取个人当天评论的个数
		$commentDayNum = $this->m->get_comment_num($this->wxid);
			
		$this->assign("timestamp", $timestamp+intval($cfg['frontTime']));
		$this->assign('timeout',$refresh-($time-$timestamp)%$refresh);
		$this->assign('refreshtime',$refresh);
		$this->assign('commentDayMax',$commentDayMax);
		$this->assign('commentMinuteMax',$commentMinuteMax);
		$this->assign('commentDayNum',$commentDayNum);
		$this->assign('placeholder',$cfg['placeholder']);
		$this->assign('staggerTime',$staggerTime);
		$this->assign('chatMaxNum',$chatMaxNum);
			
			
			
		$result = $this->m->get_special_chat($this->wxid,$commentDayNum);
		$this->assign('rule', json_encode($result));//单日
			
		$this->assign("now", $time);
		$this->display('fensi.html');
	}
	
	public function lastHongbao()
	{
		$m = Model('newYear');
		$openid = $m->get_openid($_GET['wxid']);
		if(!$_GET['wxid']||!$openid){
			$res['error'] = 1;
			$res['content'] = "很遗憾，没有抢到红包!";
			die($_REQUEST['callback']."(".json_encode($res).")");
		}
		$status = $m->get_cfg("lastHB");
		if(!$status){
			$res['error'] = 1;
			$res['content'] = "很遗憾，没有抢到红包...";
			die($_REQUEST['callback']."(".json_encode($res).")");
		}
		switch ($status)
		{
			case 1:$tvhb_id = 30;break;
			case 2:$tvhb_id = 31;break;
// 			case 3:$tvhb_id = 32;break;
			case 4:$tvhb_id = 32;break;
			case 5:$tvhb_id = 33;break;
			case 6:$tvhb_id = 34;break;
			default:$tvhb_id = 35;break;
		}
		$lottery_id =$m->getTVLottery($tvhb_id);
		$noncestr = hy_rand(28);
		$post_data = array(
				"lottery_id"=>$lottery_id,
				"noncestr"=>$noncestr,
				"userid"=>$openid,
		);
		$path = ROOT_PATH."Admin/Config/yaotv.json";
		$data = json_decode(file_get_contents($path), true);
		$stringA = $this->ToUrlParams($post_data)."&key=".$data['key'];
		$post_data['sign']=strtoupper(md5($stringA));
		$res['error'] = 0;
		$res['HB_id'] = $tvhb_id;
		$res['result'] = $post_data;
		die($_REQUEST['callback']."(".json_encode($res).")");
	}
// 	private function ToUrlParams($urlObj)
// 	{
// 		//sort($urlObj);
// 		$buff = "";
// 		foreach ($urlObj as $k => $v)
// 		{
// 			if($k != "sign"){
// 				$buff .= $k . "=" . $v . "&";
// 			}
// 		}
	
// 		$buff = trim($buff, "&");
// 		return $buff;
// 	}

    public function lastHongbaoNew()
    {
        $m = Model('rchat');
        $openid = $m->get_openid($_GET['wxid']);
        if(!$_GET['wxid']||!$openid){
            $res['error'] = 1;
            $res['content'] = "很遗憾，没有抢到红包!";
            die($_REQUEST['callback']."(".json_encode($res).")");
        }
        $tvhb_id = $m->get_new_hongbaoId();
        if(!$tvhb_id>0){
            $res['error'] = 1;
            $res['content'] = "很遗憾，没有抢到红包!!";
            die($_REQUEST['callback']."(".json_encode($res).")");
        }
        $lottery_id =$m->get_luckyDraw($tvhb_id);
        $noncestr = hy_rand(28);
        $post_data = array(
            "lottery_id"=>$lottery_id,
            "noncestr"=>$noncestr,
            "userid"=>$openid,
        );
        $path = ROOT_PATH."Admin/Config/yaotv.json";
        $data = json_decode(file_get_contents($path), true);
        $stringA = $this->ToUrlParams($post_data)."&key=".$data['key'];
        $post_data['sign']=strtoupper(md5($stringA));
        $res['error'] = 0;
        $res['HB_id'] = $tvhb_id;
        $res['result'] = $post_data;
        die($_REQUEST['callback']."(".json_encode($res).")");
    }

}